package com.xiangyang.pos.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Base64;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.xiangyang.pos.R;
import com.xiangyang.pos.adapter.OrderRecyclerViewAdapter;
import com.xiangyang.pos.bean.CommodityDataBean;
import com.xiangyang.pos.bean.OrderErrorDataBean;
import com.xiangyang.pos.constant.AppConstant;
import com.xiangyang.pos.http.HttpClient;
import com.xiangyang.pos.http.RequestParameters;
import com.xiangyang.pos.logger.Logger;
import com.xiangyang.pos.utils.SharedUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/8/18 0018.
 *
 * 生成订单（扫码展示商品）
 *
 * @author YeDalin
 *
 */

public class OrderDetailsActivity extends Activity {

    private ImageView ivGoBack;
    private RecyclerView rvOrder;
    private TextView tvAllNumber;
    private TextView tvAllMoney;
    private Button bCheckout;
    private ImageView ivScan;
    private EditText etCode;
    private Button bCode;

    private List<CommodityDataBean.CommodityData> list = new ArrayList<>();
    private OrderRecyclerViewAdapter adapter = new OrderRecyclerViewAdapter(list, this);

    private List<String> listCode = new ArrayList<>();//存储条码

    private boolean canCheckout = false;//判断是否跳转结账页面

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_details);
        initView();
        initAdapter();
        setMyClick();
        customScan();
        setDeleteMoney();
    }

    //    初始化控件
    private void initView() {
        ivGoBack = findViewById(R.id.iv_go_back);
        rvOrder = findViewById(R.id.rv_order);
        tvAllNumber = findViewById(R.id.tv_all_number);
        tvAllMoney = findViewById(R.id.tv_all_money);
        bCheckout = findViewById(R.id.b_checkout);
        ivScan = findViewById(R.id.iv_scan);
        etCode = findViewById(R.id.et_code);
        bCode = findViewById(R.id.b_code);
    }


    //    初始化适配器
    private void initAdapter() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        rvOrder.setLayoutManager(manager);
        rvOrder.setAdapter(adapter);
    }

    //    设置点击
    private void setMyClick() {
        ivGoBack.setOnClickListener(listener);
        bCheckout.setOnClickListener(listener);
        ivScan.setOnClickListener(listener);
        bCode.setOnClickListener(listener);

    }

    //    点击对象
    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.iv_scan:
                    customScan();
                    break;
                case R.id.b_checkout:
                    if (orderData()) {
                        if (canCheckout) {
                            Intent intent = new Intent(OrderDetailsActivity.this, SettlementActivity.class);
                            startActivityForResult(intent, 2000);
                        }
                    }
                    break;
                case R.id.iv_go_back:
                    cancelOrder();
                    break;
                case R.id.b_code:
                    if (getEtCode()) {
                        getHttp(etCode.getText().toString());
                        listCode.add(etCode.getText().toString());
                        etCode.setText("");
                    }
                    break;
            }
        }
    };


    //    开始扫描
    public void customScan() {
        canCheckout = false;
        new IntentIntegrator(this)
                .setOrientationLocked(false)
                .setCaptureActivity(ScanActivity.class) // 设置自定义的activity是CustomActivity
                .initiateScan(); // 初始化扫描
    }


    @Override
// 通过 onActivityResult的方法获取 扫描回来的 值
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 2000) {
            if (data != null) {
                List<OrderErrorDataBean.OrderErrorData> order = (List<OrderErrorDataBean.OrderErrorData>) data.getSerializableExtra("list");
                Logger.e("xxxx", "商品实时数量2= " + order.get(0).getNum());
                if (order != null) {
                    for (int i = 0; i < order.size(); i++) {
                        for (int j = 0; j < list.size(); j++) {
                            if (list.get(j).getCode() .equals( order.get(i).getCode())) {
                                list.get(j).setGoods_num(order.get(i).getNum());
                            }
                        }
                    }
                }
                adapter.notifyDataSetChanged();
            }
        } else {
            IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
            if (intentResult != null) {
                if (intentResult.getContents() == null) {
                    canCheckout = true;
                } else {
                    // ScanResult 为 获取到的字符串
                    String scanResult = intentResult.getContents();
                    listCode.add(scanResult);
//                setData();
                    getHttp(scanResult);

                    handler.sendEmptyMessageDelayed(1001, 1500);

                }
            } else {
                super.onActivityResult(requestCode, resultCode, data);
            }
        }


    }

    //    重复扫描
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1001) {
                customScan();
            }
        }
    };


    //    制作假数据
    private void setData() {
        CommodityDataBean.CommodityData data = new CommodityDataBean().new CommodityData();
        data.setGoods_name("精品猪肉");
        data.setPrice(3012);
        if (list.size() != 0) {
            for (int i = 0; i < list.size(); i++) {

            }
        }
        data.setCount(1);

        list.add(data);
        adapter.notifyDataSetChanged();
        setTvAllMoney();
    }


    /**
     * 添加网络获取的数据
     * 注意：网络获取的数据没有count（数量），需要自己计算设置
     * 添加标准为——当名字与价格相同时加1
     */
    private void setData(CommodityDataBean.CommodityData bean) {
        /*if (list.size() == 0) {

            if(bean.getCount()>bean.getGoods_num()){



            }else {
                bean.setCount(1);
                list.add(bean);
                changeData(1);
                return;
            }
        }*/

        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getCode() .equals(bean.getCode()) ) {

                if (list.get(i).getCount() >= bean.getGoods_num()) {
                    //超过限制
                    noHaveCommodity();
                    return;
                } else {
                    list.get(i).setCount(list.get(i).getCount() + 1);
                    changeData(i);
                    return;
                }
            }
        }


        if (bean.getCount() > bean.getGoods_num()) {
            //超过限制
            noHaveCommodity();
            return;
        } else {
            bean.setCount(1);
            list.add(bean);
            changeData(list.size() - 1);
            return;
        }

    }


    //    更新数据
    private void changeData(int position) {
        adapter.notifyDataSetChanged();

        rvOrder.smoothScrollToPosition(position);

        setTvAllMoney();
    }


    //    计算金额
    private void setTvAllMoney() {

        int count = 0;
        int money = 0;
        for (int i = 0; i < list.size(); i++) {
            count = count + list.get(i).getCount();
            money = list.get(i).getIntPrice() * list.get(i).getCount() + money;
        }


        tvAllNumber.setText("" + count);
        tvAllMoney.setText("￥" + (money / 100.00));
        SharedUtils.setIntPrefs(OrderDetailsActivity.this, "all_money", money);

    }

    //    删除商品，回调计算金额
    private void setDeleteMoney() {
        if (adapter != null) {
            adapter.setDeleteData(new OrderRecyclerViewAdapter.DeleteData() {
                @Override
                public void setAllMoney(int position, boolean isDelete) {
                    setTvAllMoney();//重新计算商品总价
                    if (isDelete) {
                        listCode.remove(position);//刪除商品条码集合（条码集合与商品集合不是同一个集合，要分别处理）
                    }
                }
            });
        }
    }


    //    存储数据
    private boolean orderData() {
        if (list.size() == 0) {
            Toast.makeText(OrderDetailsActivity.this, "买点东西再来结账吧", Toast.LENGTH_SHORT).show();
            return false;
        }


        /*Gson gson = new Gson();
        String str = gson.toJson(listCode);*/


//        php解析异常，进行重新拼接商品条码
        String str = "";
        for (int i = 0; i < listCode.size(); i++) {
            str = str + listCode.get(i) + "-";
        }

        SharedUtils.setStringPrefs(OrderDetailsActivity.this, "list_code", str);

        String content = "[";
        for (int i = 0; i < list.size(); i++) {
            String s = "{\"2\":\"" + list.get(i).getCode() + "\",\"5\":\"" + list.get(i).getCount() + "\"}";
            if (i != list.size() - 1) {
                s = s + ",";
            }
            content = content + s;
        }
        content = content + "]";
        Logger.e("xxxx", "content=" + content);
        content = Base64.encodeToString(content.getBytes(), Base64.NO_CLOSE);
        Logger.e("xxxx", "content= " + content);
        Logger.e("xxxx", "content= " + content.length());
        content = content.substring(0, content.length() - 1);
        Logger.e("xxxx", "content= " + content);
        Logger.e("xxxx", "content= " + content.length());
        SharedUtils.setStringPrefs(this, "content", content);

        String listStr = "";
        for (int i = 0; i < list.size(); i++) {
            listStr = listStr + list.get(i).getGoods_name() + "  "
                    + list.get(i).getCount() + "* ￥" + list.get(i).getPrice()
                    + "小计:￥" + list.get(i).getCount() * list.get(i).getPrice() + "\n";
        }

        SharedUtils.setStringPrefs(OrderDetailsActivity.this, "list_order", listStr);

        return true;
    }

    //查询商品（网络访问）
    private void getHttp(String scanResult) {
        String UserTOKEN = SharedUtils.getStringPrefs(this, "UserTOKEN", "");
//        final String COMMODITY_URL= AppConstant.POS_URL+"/Goods/An/goodslist/u="+apiToken;
        final String COMMODITY_URL = AppConstant.POS_URL + "/Goods/An/goodsList/u=" + UserTOKEN;


        Logger.e("xxxx", COMMODITY_URL);

        HttpClient httpClient = new HttpClient();
        httpClient.post(COMMODITY_URL, getCode(scanResult), new HttpClient.OnResponseListener() {
            @Override
            public void onResponse(String result) {
                if (!result.equals("Error")) {

                    Logger.e("xxxx", "order result = " + result);

                    Gson gson = new Gson();
                    CommodityDataBean bean = gson.fromJson(result, CommodityDataBean.class);
                    if (bean != null) {
                        if (bean.getStatus() == 1) {
                            Logger.e("xxxx", "name = " + bean.getData().getGoods_name());
                            setData(bean.getData());
                        } else {
                            Logger.e("xxx", bean.getMsg());
                            noHaveCommodity();
                        }
                    }
                } else {
                    Toast.makeText(OrderDetailsActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    //    上传条码
    private RequestParameters getCode(String scanResult) {
        RequestParameters parameters = new RequestParameters();
        parameters.put("code", scanResult);
        parameters.put("shopid",SharedUtils.getStringPrefs(this,"shopId",""));
        return parameters;
    }


    //    是否取消订单对话框
    private void cancelOrder() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(false);
        builder.setTitle("确定要取消订单");
        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                finish();
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                builder.setCancelable(true);
            }
        });
        builder.show();
    }

    //    点击返回弹出对话框
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            cancelOrder();
        }
        return super.onKeyDown(keyCode, event);
    }

    //判断输入框是否为空
    private boolean getEtCode() {
        if (etCode.getText().toString().length() == 0) {
            return false;
        }
        return true;
    }


    //    达到商品上限对话框
    private void noHaveCommodity() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(false);
        builder.setTitle("该商品已被APP用户买走");
        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                builder.setCancelable(true);
            }
        });
        builder.show();
    }

}
